package ynu.edu.achitectureclass.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ynu.edu.achitectureclass.entity.CameraData;
import ynu.edu.achitectureclass.service.CameraDataService;
import ynu.edu.achitectureclass.service.DeviceService;

import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@RestController
@RequestMapping("/api/camera_data")
public class CameraDataController {

    @Autowired
    private CameraDataService cameraDataService;
    @Autowired
    private DeviceService deviceService;

    // 获取 accessToken 并传递给前端
    @GetMapping("/token")
    public String getAccessToken() {
        return cameraDataService.getAccessToken();
    }

    @PostMapping("/catch_img")
    public void captureImage() {
        String deviceSerial = deviceService.getCameraDeviceSerial();
        System.out.println(deviceSerial);

        // 如果设备号为空，则返回错误信息
        if (deviceSerial == null || deviceSerial.isEmpty()) {
            throw new RuntimeException("未找到类型为 camera 的设备");
        }
        cameraDataService.captureAndSaveImage(deviceSerial);
    }

    // 获取所有历史记录
    @GetMapping("/history")
    public List<CameraData> getCameraDataHistory() {
        List<CameraData> cameraDataList = cameraDataService.getAllCameraData();
        // 将 localImagePath 转换为相对路径
        for (CameraData cameraData : cameraDataList) {
            if (cameraData.getLocalImagePath() != null) {
                // 将绝对路径转换为相对路径
                String relativePath = convertToRelativePath(cameraData.getLocalImagePath());
                cameraData.setLocalImagePath(relativePath);
            }
        }
        return cameraDataList;
    }

    // 将绝对路径转换为相对路径
    private String convertToRelativePath(String absolutePath) {
        // 假设图片存储在项目的 resources/image 目录下
        String projectRoot = Paths.get("").toAbsolutePath().toString();
        String imageStoragePath = projectRoot + "/src/main/resources/image/";

        if (absolutePath.startsWith(imageStoragePath)) {
            return absolutePath.substring(imageStoragePath.length());
        }
        return absolutePath; // 如果路径不符合预期，直接返回原路径
    }

    // 根据相对路径返回图片
    @GetMapping("/image/{filename:.+}")
    public ResponseEntity<Resource> getImage(@PathVariable String filename) {
        try {
            // 构建图片的本地路径
            Path imagePath = Paths.get("src/main/resources/image").resolve(filename).toAbsolutePath();
            Resource resource = new UrlResource(imagePath.toUri());

            if (resource.exists() || resource.isReadable()) {
                // 设置响应头
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.IMAGE_JPEG); // 根据图片类型设置 Content-Type

                return ResponseEntity.ok()
                        .headers(headers)
                        .body(resource);
            } else {
                throw new RuntimeException("无法读取图片: " + filename);
            }
        } catch (MalformedURLException e) {
            throw new RuntimeException("图片路径错误: " + filename, e);
        }
    }
}